跳到主要内容

JZ54 字符流中第一个不重复的字符

https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720

第一次解:

直接使用暴力法解

import java.util.*;

public class Solution {
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
char single = '#';

public void Insert(char ch) {
if (!map.containsKey(ch)) {
map.put(ch, 1);
if (single == '#') {
single = ch;
}
} else {
map.put(ch, map.getOrDefault(ch, 1) + 1);
if (ch == single) {
single = '#';
// 这里取第一个不重复的值
for (Map.Entry<Character, Integer> entity : map.entrySet()) {
if (entity.getValue() == 1) {
single = entity.getKey();
break;
}
}
}
}
}

//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
return single;
}
}